import { RouteRecordRaw } from "vue-router";

let firstMenu: any = null

export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
 const routes: RouteRecordRaw[] = []

  //  1.加载默认所有routes
  const allRoutes: RouteRecordRaw[] = []
  const routerFiles = require.context('../router/main', true, /\.ts/);
  routerFiles.keys().forEach( key => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  const _recurseGetRoute = (menus: any[]) => {
    for(const menu of menus) {
      if(menu.type === 2) {
        const route = allRoutes.find(route => route.path === menu.url)
        if(route) routes.push(route)
        if(!firstMenu) { firstMenu = menu }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)
  return routes
}

export function pathMapToMenu(userMenus: any[], currenPath: string): any {
  for (const menu of userMenus) {
    if(menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children, currenPath)
      if(findMenu) { return findMenu }
    } else if ( menu.type === 2 && menu.url === currenPath) {
      return menu
    }
  }
}

// 根据菜单获取所有的按钮权限
export function menuMapToPermissions(userMenus: any[]) {
  const permissions: string[] = []

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)

  return permissions
}

export function getMenuChecks(menuList: any[]): number[] {
  const checks: number[] = []
  const _recurseGetChecked = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetChecked(menu.children)
      } else {
        checks.push(menu.id)
      }
    }
  }
  _recurseGetChecked(menuList)
  return checks
}

export { firstMenu }
